package com.china08.yxyapi.api.manage.stu.mystudy.huixue.scoreimprove;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.questionbank.YxyQuesbankKnowlegeRelFoundationKnowlege;
import com.china08.yxyapi.entity.db.res.YxyResResource;
import com.china08.yxyapi.entity.es.ElasticYxyResResource;
import com.china08.yxyapi.entity.mg.user.YxyUserMark;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.huixue.comm.YxyQuesbankKnowlegeRelFoundationKnowlegeRepository;
import com.china08.yxyapi.repository.mg.YxyUserFavorRepository;
import com.china08.yxyapi.security.profile.YxyProfile;
import com.china08.yxyapi.service.res.huixue.impl.PlanKnowWeikeServiceImpl;
import com.china08.yxyapi.util.YxyPlayUrlForWeiKechengBuilder;
import com.china08.yxyapi.util.YxyResUtil;

/**
 * 学习计划——看视频
 */
@RestController
public class PlanWeikeSchController extends YxyApiBaseController {

    @Autowired
    private PlanKnowWeikeServiceImpl planKnowWeikeServiceImpl;

    @Autowired
    private YxyPlayUrlForWeiKechengBuilder builder;

    @Autowired
    private YxyUserFavorRepository favorRepository;

    @Autowired
    private MongoTemplate mt;

    @Autowired
    private YxyQuesbankKnowlegeRelFoundationKnowlegeRepository yxyQuesbankKnowlegeRelFoundationKnowlegeRepository;

    @RequestMapping(value = "/api_yw/manage/stu/mystudy/huixue/scoreimprove/weike", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public List<RespModel> precess(HttpServletRequest request, HttpServletResponse response,
            @RequestBody ReqModel reqModel) {
        YxyProfile profile = getProfile(request, response);

        // 用户属性
        String userId = profile.getId();

        List<YxyQuesbankKnowlegeRelFoundationKnowlege> knowleges = yxyQuesbankKnowlegeRelFoundationKnowlegeRepository
                .findByKnowId(reqModel.kid);
        List<String> knows = new ArrayList<String>();

        for (YxyQuesbankKnowlegeRelFoundationKnowlege oldKnow : knowleges) {
            knows.add(oldKnow.getFoundationKnowId());
        }

        List<YxyResResource> yrrLst = planKnowWeikeServiceImpl.getWeiKeForPlanKnow(knows);
        List<RespModel> respModels = new ArrayList<RespModel>();
        for (YxyResResource yxyResResource : yrrLst) {
            RespModel respModel = new RespModel();

            // respModel.url = yxyResUtil.getPreviewUrl(yxyResResource.getId());
            // 视频路径
            String url = builder.setResourceId(yxyResResource.getId()).setUserId(userId)
                    .setUserVip(BooleanUtils.toBoolean(profile.getUserVip()))
                    .setResVip(BooleanUtils.toBoolean(profile.getResVip())).setViewFrom("huixue").build();
            respModel.url = url;

            respModel.wid = yxyResResource.getId();
            respModel.cover = yxyResResource.getCover();
            respModel.showTitle = yxyResResource.getTitle();
            respModel.uploaderId = yxyResResource.getUploaderId();
            respModel.uploaderName = yxyResResource.getUploaderName();
            respModel.mark = yxyResResource.getMark();
            respModel.pv = yxyResResource.getPv();
            respModel.favCount = yxyResResource.getFavoriteCount();
            respModel.isVip = yxyResResource.getIsVip();

            // 是否收藏
            if (StringUtils.isNotBlank(userId)) {
                String schoolId = getProfile(request, response).getSchoolId();
                if (StringUtils.isNotBlank(schoolId)) {

                    // String roleId = getProfile(request,
                    // response).getRoleId();
                    // 用户的角色 使用云校接口
                    // String url = YX_API_PATH + "/comm/user/role/" + userId +
                    // "/"
                    // + roleId + "/" + schoolId;
                    // RestTemplate rt = new RestTemplate();
                    //
                    // String userRoleId = rt.getForObject(url, String.class);

                    long myfavCount = favorRepository.countByResIdAndUserId(yxyResResource.getId(), userId);

                    respModel.ifFavorite = myfavCount > 0 ? true : false;
                    // 我的评分
                    YxyUserMark mark = mt.findOne(
                            new Query().addCriteria(
                                    Criteria.where("resId").is(yxyResResource.getId()).and("userId").is(userId)),
                            YxyUserMark.class);
                    Integer myMark = (mark == null ? -1 : mark.getMark());
                    respModel.myMark = myMark;
                } else {
                    respModel.ifFavorite = false;
                    respModel.myMark = -1;
                }
            }
            Long markCount = mt.count(new Query().addCriteria(Criteria.where("resId").is(yxyResResource.getId())),
                    YxyUserMark.class);
            respModel.markCount = markCount;
            ElasticYxyResResource resResource = new ElasticYxyResResource();
            resResource.setDuration(yxyResResource.getDuration());
            respModel.duration = YxyResUtil.getDurationString(resResource);
            SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd");
            respModel.uploadTime = sdFormat.format(yxyResResource.getUploadTime());
            respModel.intro = yxyResResource.getIntro();

            /*
             * if (yxyResResource.getUploaderId() == teaId) {
             * respModel.showTitle = yxyResResource.getUploaderName() + "视频讲解："
             * + yxyResResource.getTitle(); } else { respModel.showTitle = "微课："
             * + yxyResResource.getTitle(); }
             */
            respModels.add(respModel);
        }

        return respModels;
    }

    /**
     * 请求参数
     * 
     */
    protected static class ReqModel extends YxyApiReqModel {
        // 知识点章节id
        public String kid;
    }

    /**
     * 响应参数
     * 
     */
    protected static class RespModel extends YxyApiRespModel {
        // 微课视频链接地址
        public String url;

        // 展示标题（区分老师与微课）
        public String showTitle;

        // 微课封面
        public String cover;

        public String wid;

        public String uploaderId;// 上传者id

        public String uploaderName;// 上传者名称 *

        public String uploaderIntro;// 上传者简介 *

        public float mark;// 评分 *

        public Long pv;// 浏览次数 *

        public boolean ifFavorite;// 是否收藏 *

        public Long favCount;// 收藏次数 *

        public Long markCount;// 评价次数 *

        public String duration;// 时长 *

        public String uploadTime;// 上传时间 *

        public String intro;// 微课简介 *

        public Integer myMark;// 我的上次评分 *

        public boolean isVip;// 是否vip
    }
}
